<template>
  <el-dialog :visible.sync="visible" title="上传活动" v-loading="isLoading">
    <el-form ref="form" :model="form" label-width="120px">
      <!-- 活动照片上传 -->
      <el-form-item label="活动照片" required>
        <el-upload
          ref="activityPhoto"
          :file-list="activityPhotoList"
          list-type="picture-card"
          action="#"
          :http-request="uploadActivityPhoto"
          :before-upload="beforeUploadImage"
          :show-file-list="false">
          <i class="el-icon-plus" v-if="!form.activityPictureUrl"></i>
          <img
            v-else
            :src="form.activityPictureUrl"
            width="100%"
            height="100%" />
        </el-upload>
      </el-form-item>

      <!-- 活动事项输入 -->
      <el-form-item label="活动事项">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入活动事项"
          v-model="form.activityContent"></el-input>
      </el-form-item>
      <!-- 服务时长输入 -->
      <el-form-item label="服务时长">
        <el-input-number
          v-model="form.activityTime"
          :min="0"
          :max="24"></el-input-number>
        小时
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      isLoading: false,
      visible: false,
      form: {
        activityPictureUrl: "",
        activityContent: "",
        activityTime: "",
      },
      activityPhotoList: [],
      activityPhotoVisible: false,
    };
  },
  methods: {
    uploadActivityPhoto({ file }) {
      this.isLoading = true;

      // 使用你的API服务替换下面的URL
      request
        .uploadFileRequest("/api/upload/activity", { file: file })
        .then((res) => {
          this.isLoading = false;
          this.form.activityPictureUrl = res.data.data;
        })
        .catch(() => {
          this.isLoading = false;
        });
    },
    beforeUploadImage(file) {
      const isImage = file.type.startsWith("image");
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isImage) {
        this.$message.error("只能上传图片!");
      }
      if (!isLt10M) {
        this.$message.error("图片大小不能超过 10MB!");
      }
      return isImage && isLt10M;
    },
    submitForm() {
      this.isLoading = true;
      request.postRequest("api/activity/save", this.form).then((res) => {
        this.isLoading = false;
        if (res.data.code === 0) {
          this.$message({
            type: "success",
            message: "提交成功",
          });
          this.form = {
            activityPictureUrl: "",
            activityContent: "",
            activityTime: "",
          };
          this.visible = false;
          this.$emit("getData");
        }
      });
    },
  },
};
</script>

<style scoped>
/* 这里可以添加一些样式 */
</style>
